package com.mianle.userapi.util;

import com.google.gson.Gson;
import com.mianle.userapi.config.QiNiuConfig;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import com.qiniu.util.UrlSafeBase64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.Random;

public class QiNiuTool {
    private static  final  String IMAGETYPE_s_120 = "s120";
    private static  final  String IMAGETYPE_s_480 = "s480";


    private static final Logger log= LoggerFactory.getLogger(QiNiuTool.class);
    public String start(HttpServletRequest request, QiNiuConfig qiNiuConfig, String fops, String pipeline)throws Exception {
        String filePath = "";
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        if (multipartResolver.isMultipart(request)) {
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;

            Iterator<String> iter = multiRequest.getFileNames();

            while (iter.hasNext()) {
                MultipartFile file = multiRequest.getFile(iter.next());
                String fileName = file.getOriginalFilename();
                String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
                SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
                String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
                DefaultPutRet putRet = upload(qiNiuConfig, file.getBytes(), newFileName,fops,pipeline);
                //filePath += qiNiuConfig.getBucketUrl() + "_" + putRet.key + ",";
                filePath += putRet.key + ",";

            }
            if (filePath.endsWith(",")) {
                filePath = filePath.substring(0, filePath.length() - 1);
            }
        }
        return filePath;
    }

    /**
     * 七牛上传图片
     * @param qiNiuConfig 七牛配置
     * @param file 上传文件二进制
     * @param key  文件名标识
     * @param fops 图片处理 基本处理和高级处理
     * @param pipeline
     * @return
     * @throws Exception
     */
    public DefaultPutRet upload(QiNiuConfig qiNiuConfig,byte[] file, String key,String fops,String pipeline) throws Exception {

        String urlbase64 = UrlSafeBase64.encodeToString(qiNiuConfig.getBucket()+":"+key);
        String pfops = fops + "|saveas/" + urlbase64;

        Auth auth = Auth.create(qiNiuConfig.getAccessKey(), qiNiuConfig.getSecretKey());
        Zone z = Zone.autoZone();
        Configuration c = new Configuration(z);
        UploadManager uploadManager = new UploadManager(c);
        Response res = uploadManager.put(file, key, getUpToken(auth, qiNiuConfig.getBucket(),pfops,pipeline));
        DefaultPutRet putRet = new Gson().fromJson(res.bodyString(), DefaultPutRet.class);
        return putRet;
    }

    /**
     * 获取上传凭证
     * @param auth
     * @param bucketname
     * @param pfops 预转数据处理指令 avthumb/flv|saveas/cWJ1Y2tldDpxa2V5
     * @param pipeline
     * @return
     */
    public String getUpToken(Auth auth, String bucketname,String pfops,String pipeline) {
        return auth.uploadToken(bucketname,null,3600,new StringMap()
                .putNotEmpty("persistentOps", pfops)
                .putNotEmpty("persistentPipeline", pipeline), true);
    }

    public static String doUpload(HttpServletRequest request,QiNiuConfig qiNiuConfig){
        QiNiuTool qiNiuTool = new QiNiuTool();
        String type = request.getParameter("type");
        String fops = "";
        if (type!=null && IMAGETYPE_s_120.equalsIgnoreCase(type)) {
            fops = qiNiuConfig.getSquare120();
        }
        else if(type!=null && IMAGETYPE_s_480.equalsIgnoreCase(type)){
            fops = qiNiuConfig.getSquare480();
        }
        else{
            fops = qiNiuConfig.getRectangle480auto();
        }
        String filePath = "";
        try{
            filePath = qiNiuTool.start(request,qiNiuConfig,fops,"");
            return filePath;
        }catch (Exception ex){
            log.error(ex.getMessage());
            return null;
        }
    }

    public void delImage(QiNiuConfig qiNiuConfig,String imageName){
        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(Zone.zone0());
        Auth auth = Auth.create(qiNiuConfig.getAccessKey(), qiNiuConfig.getSecretKey());
        BucketManager bucketManager = new BucketManager(auth, cfg);
        try {
            bucketManager.delete(qiNiuConfig.getBucket(), imageName);
        } catch (QiniuException ex) {
            //如果遇到异常，说明删除失败
            System.err.println(ex.code());
            System.err.println(ex.response.toString());
        }
    }
}
